import React, { useState, useEffect, Fragment, useCallback } from "react";
import Handsontable from "handsontable";
import { HotTable } from "@handsontable/react";
import "handsontable/languages/zh-CN";
import { Button, message, Space, Modal } from "antd";
import Api from "./api";

export default function Log() {
  // setSetting({ ...setSetting, mergeCells: mergeData });
  // console.log(tableState)
  const [setting, setSetting] = useState({
    licenseKey: "non-commercial-and-evaluation",
  });

  const [tableState, setTableState] = useState([]);
  const hotTableComponent = React.createRef();

  // useEffect(() => {

  // }, []);

  const checkWholeValid = () => {
    let result = true;
    tableState.forEach((item) => {
      item.forEach((inner) => {
        // console.log(inner);
        if (!inner) {
          result = false;
          return;
        }
      });
    });

    return result;
  };

  // const initialTableState=()=>{
  //   if(!tableState) {

  //     setTableState(initial)
  //   }
  // }

  useEffect(() => {
    // initialTableState()
    const data = [
      [
        "上级部门部署的工作 ",
        "党风廉政建设工作",
        "规范加油卡管理",
        "1、开展自查",
        "2020-11-20",
        2,
        "标准1",
      ],
      [null, null, null, "2、完成自查自纠报告", "2020-11-10", 2, null],
      [null, null, null, "2、完成自查自纠报告", null, 2, null],
      ["大类1", "类型2", "类型3", "2、完成自查自纠报告", null, 2, null],
      [null, "类型2", "类型3", "2、完成自查自纠报告", null, 2, null],
    ];

    // this.state = {
    //   // isValid: false,
    //   setting: { ...this.initialSetting },

    //   tableState: tmp,
    // };

    // const [isValid, setIsValid] = useState(true);
    // const [setting, setSetting] = useState(initialSetting);
    // }

    // console.log(mergeData);
    const dataSpan = new Array(data.length);
    const mergeData = [];

    // constructor(props) {
    //   super(props);

    data.forEach((item, index) => {
      dataSpan[index] = new Array(11).fill(1);
      Object.keys(item).forEach((innerItem, innerIndex) => {
        // console.log(index, innerItem, innerIndex, item[innerItem]);
        if (index > 0) {
          if (!item[innerItem]) {
            for (let i = index - 1; i > -1; i--) {
              if (data[i][innerItem]) {
                dataSpan[i][innerIndex] += 1;
                return;
              }
            }
          }
        }
      });
    });
    // console.log(this.dataSpan);

    dataSpan.forEach((item, index) => {
      item.forEach((innerItem, innerIndex) => {
        if (innerItem > 1) {
          mergeData.push({
            row: index,
            col: innerIndex,
            rowspan: innerItem,
            colspan: 1,
          });
        }
      });
    });
    console.log(mergeData);

    const initialSetting = {
      // colHeaders: true,
      rowHeaders: true,
      colHeaders: [
        "一级指标",
        "二级指标",
        "三级指标",
        "关键步骤",
        "完成时限",
        "分值",
        "评分标准",
        "目标来源",
        "责任部门",
        "分管领导/责任人",
        "有关责任人",
        "相关附件",
      ],
      mergeCells: mergeData,
      manualColumnResize: true,
      manualRowResize: true,
      width: "100%",
      height: 680,
      className: "htMiddle", //https://handsontable.com/docs/8.1.0/demo-alignment.html
      minSpareRows: 1,
      rowHeights: 36,
      colWidths: [200, 200, 200, 260, 120, 80, 180, 160, 160, 160, 160, 100],
      contextMenu: [
        "row_above",
        "row_below",
        "clear_column",
        "remove_row",
        "---------",
        "mergeCells",
        "make_read_only",
        "alignment",
      ],
      columns: [
        {
          data: 0,
          allowEmpty: false,
        },
        {
          data: 1,
        },
        {
          data: 2,
        },
        {
          data: 3,
        },
        {
          data: 4,
          type: "date",
          dateFormat: "YYYY-MM-DD",
          datePickerConfig: {
            i18n: {
              previousMonth: "上月",
              nextMonth: "下月",
              months: [
                "一月",
                "二月",
                "三月",
                "四月",
                "五月",
                "六月",
                "七月",
                "八月",
                "九月",
                "十月",
                "十一月",
                "十二月",
              ],
              weekdays: [
                "星期日",
                "星期一",
                "星期二",
                "星期三",
                "星期四",
                "星期五",
                "星期六",
              ],
              weekdaysShort: [
                "周日",
                "周一",
                "周二",
                "周三",
                "周四",
                "周五",
                "周六",
              ],
            },
          },
        },
        {
          data: 5,
          type: "numeric",
        },
        {
          data: 6,
          editor: "select",
          selectOptions: ["标准1", "标准2", "标准3", "标准4"],
        },
        {
          data: 7,
          editor: "select",
          selectOptions: ["目标来源1", "目标来源2", "目标来源3", "目标来源4"],
        },
        {
          data: 8,
          editor: "select",
          selectOptions: ["责任部门1", "责任部门2", "责任部门3", "责任部门4"],
        },
        {
          data: 9,
          editor: "select",
          selectOptions: [
            "分管领导/责任人1",
            "分管领导/责任人2",
            "分管领导/责任人3",
            "分管领导/责任人4",
          ],
        },
        {
          data: 10,
          editor: "select",
          selectOptions: [
            "有关责任人1",
            "有关责任人2",
            "有关责任人3",
            "有关责任人4",
          ],
        },
        {
          readOnly: true,
          // data:11,
          renderer: (instance, td, row, col, prop, value, cellProperties) => {
            console.log(instance, td, row, col, prop, value, cellProperties);
            if (row == data.length - 1) {
              return;
            }
            let button = document.createElement("button");
            button.className = "ant-btn ant-btn-primary ant-btn-sm";
            let t = document.createTextNode("附件管理");
            button.appendChild(t);

            Handsontable.dom.addEvent(button, "click", function (event) {
              console.log(event);

              setAttachmentVisible(true);

              // file.click()
              event.preventDefault();
            });

            Handsontable.dom.empty(td);

            td.appendChild(button);

            td.className = "htMiddle htCenter";

            return td;
          },
        },
      ],
      data,
      licenseKey: "non-commercial-and-evaluation",
    };

    setSetting(initialSetting);

    const initial = new Array(data.length);
    for (let i = 0; i < data.length; i++) {
      initial[i] = new Array(11).fill(true);
    }

    setTableState(initial);

    const validateCallback = (isValided, value, row, col) => {
      console.log(isValided, value, row, col);
      // console.log(tableState)
      // initialTableState()

      let tmp;
      if (tableState.length == 0) {
        tmp = initial;
      } else {
        tmp = Object.assign({}, tableState);
      }

      // console.log(tmp);

      if (row > tmp.length - 1) {
        for (let i = row; i > tmp.length - 2; i--) {
          console.log(i);
          tmp.push(new Array(11).fill(true));
        }
      }
      tmp[row][col] = isValided;

      setTableState(tmp);

      return isValided;
    };

    const removeCallback = (index, amount, data) => {
      console.log(index, amount, data);
      // initialTableState()
      // console.log(tableState)

      let tmp;
      if (tableState.length == 0) {
        tmp = initial;
      } else {
        tmp = Object.assign({}, tableState);
      }

      tmp.splice(index, amount);
      console.log(tmp);
      setTableState(tmp);
    };
    Handsontable.hooks.add(
      "afterValidate",
      [validateCallback],
      hotTableComponent.current.hotInstance
    );

    Handsontable.hooks.add(
      "afterRemoveRow",
      [removeCallback],
      hotTableComponent.current.hotInstance
    );
  }, []);

  const [attachmentVisible, setAttachmentVisible] = useState(false);

  const getTableData = () => {
    let tmp;
    if (hotTableComponent.current) {
      tmp = hotTableComponent.current.hotInstance.getData();
      console.log(hotTableComponent.current.hotInstance);
    }

    console.log(tableState);
    if (!checkWholeValid()) {
      message.error("数据校验错误");
    }

    tmp.splice(tmp.length - 1, 1); // 删除最后一行
    console.log(tmp);
    // setResult(tmp);
    message.info(tmp);
  };
  // render() {
  return (
    <Fragment>
      <Space style={{ marginBottom: "10px" }}>
        <Button
          type="primary"
          //
          onClick={
            () =>
              // this.setState({
              //   setting: { ...this.initialSetting, data: [], mergeCells: [] },
              setSetting({ ...setting, data: [], mergeCells: [] })
            // })
          }
        >
          新建
        </Button>
        <Button
          type="primary"
          // style={{ marginBottom: "10px" }}
          onClick={() => getTableData()}
        >
          获取数据
        </Button>
      </Space>
      {/* {result?<div>{result}</div>:''} */}

      <HotTable
        ref={hotTableComponent}
        language="zh-CN"
        settings={setting}
        style={{ width: "100%" }}
      />

      <Modal
        visible={attachmentVisible}
        maskClosable={false}
        title="附件管理"
        width={"800px"}
        // onOk={handleOk}
        onCancel={() => {
          setAttachmentVisible(false);
        }}
        footer={null}
      >
        <Api />
      </Modal>
    </Fragment>
  );
  // }
}
/*

上级部门部署的工作      党风廉政建设工作                       
                                      纠治“四风”
                                      数据信息报送
*/
